package com.example.backend.controller;

import com.example.backend.security.RequirePermission;
import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.TicketPriority;
import com.example.backend.dto.ApiResponse;
import com.example.backend.dto.TicketDto;
import com.example.backend.mapper.SimpleMappers;
import com.example.backend.service.TicketServiceOptimized;
import com.example.backend.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 优化的工单Controller
 * 快速响应 API
 */
@RestController
@RequestMapping("/api/v2/tickets")
@Tag(name = "工单管理（优化版）", description = "高性能工单创建接口")
@SecurityRequirement(name = "Bearer Authentication")
public class TicketControllerOptimized {
    
    private static final Logger log = LoggerFactory.getLogger(TicketControllerOptimized.class);
    
    private final TicketServiceOptimized ticketServiceOptimized;
    private final UserService userService;
    
    public TicketControllerOptimized(
            TicketServiceOptimized ticketServiceOptimized,
            UserService userService) {
        this.ticketServiceOptimized = ticketServiceOptimized;
        this.userService = userService;
    }
    
    /**
     * 创建工单请求DTO
     */
    public record CreateTicketRequest(
            @NotBlank @Size(max = 200) String title,
            @NotBlank @Size(max = 2000) String description,
            String descriptionDetail,
            Long categoryId,
            TicketPriority priority,
            Long creatorId,
            Long customerId) {}
    
    /**
     * 创建工单（优化版）
     * 性能优化：
     * 1. 最小化同步操作
     * 2. 快速数据库保存
     * 3. 异步处理复杂逻辑
     * 4. 立即返回响应
     */
    @PostMapping
    @Operation(summary = "创建工单（优化版）", 
               description = "高性能工单创建，快速响应 + 异步处理")
    @RequirePermission(roles = {"CUSTOMER", "AGENT", "ADMIN"})
    public ResponseEntity<ApiResponse<TicketDto>> createOptimized(@Valid @RequestBody CreateTicketRequest req) {
        String requestId = "API-OPT-" + System.currentTimeMillis();
        long startTime = System.currentTimeMillis();
        
        try {
            log.info("╔═══════════════════════════════════════════════════════════════");
            log.info("║ [{}] ⚡ 收到优化版工单创建请求", requestId);
            log.info("╠═══════════════════════════════════════════════════════════════");
            log.info("║ 标题: {}", req.title());
            log.info("║ 优先级: {}", req.priority());
            log.info("║ 创建者ID: {}", req.creatorId());
            log.info("╚═══════════════════════════════════════════════════════════════");
            
            // 步骤1：验证用户（快速查询）
            long step1Start = System.currentTimeMillis();
            User creator = userService.findById(req.creatorId())
                    .orElseThrow(() -> new RuntimeException("创建者不存在，ID: " + req.creatorId()));
            long step1Time = System.currentTimeMillis() - step1Start;
            log.debug("[{}] ✓ 用户验证 - {}ms", requestId, step1Time);
            
            // 步骤2：构建工单实体（内存操作）
            long step2Start = System.currentTimeMillis();
            User customer = req.customerId() != null ? 
                    userService.findById(req.customerId()).orElse(creator) : creator;
            
            Ticket ticket = Ticket.builder()
                    .title(req.title())
                    .description(req.description())
                    .descriptionDetail(req.descriptionDetail())
                    .priority(req.priority() != null ? req.priority() : TicketPriority.MEDIUM)
                    .createdBy(creator)
                    .customer(customer)
                    .build();
            long step2Time = System.currentTimeMillis() - step2Start;
            log.debug("[{}] ✓ 实体构建 - {}ms", requestId, step2Time);
            
            // 步骤3：保存工单（优化版Service）
            long step3Start = System.currentTimeMillis();
            Ticket saved = ticketServiceOptimized.createOptimized(ticket, creator);
            long step3Time = System.currentTimeMillis() - step3Start;
            log.info("[{}] ✓ 工单保存 - {}ms", requestId, step3Time);
            
            // 步骤4：转换DTO（轻量操作）
            long step4Start = System.currentTimeMillis();
            TicketDto dto = SimpleMappers.toTicketDto(saved);
            long step4Time = System.currentTimeMillis() - step4Start;
            log.debug("[{}] ✓ DTO转换 - {}ms", requestId, step4Time);
            
            // 计算总耗时
            long totalTime = System.currentTimeMillis() - startTime;
            
            log.info("╔═══════════════════════════════════════════════════════════════");
            log.info("║ [{}] ✅ 优化版工单创建完成", requestId);
            log.info("╠═══════════════════════════════════════════════════════════════");
            log.info("║ 工单ID: {}", saved.getId());
            log.info("║ 工单编号: {}", saved.getTicketNumber());
            log.info("║ API总耗时: {}ms", totalTime);
            log.info("║   - 用户验证: {}ms", step1Time);
            log.info("║   - 实体构建: {}ms", step2Time);
            log.info("║   - 工单保存: {}ms", step3Time);
            log.info("║   - DTO转换: {}ms", step4Time);
            log.info("║ 💡 复杂业务逻辑正在异步处理中", "");
            log.info("╚═══════════════════════════════════════════════════════════════");
            
            return ResponseEntity.ok(ApiResponse.success("工单创建成功", dto));
            
        } catch (Exception e) {
            long errorTime = System.currentTimeMillis() - startTime;
            
            log.error("╔═══════════════════════════════════════════════════════════════");
            log.error("║ [{}] ❌ 优化版工单创建失败", requestId);
            log.error("╠═══════════════════════════════════════════════════════════════");
            log.error("║ 耗时: {}ms", errorTime);
            log.error("║ 异常: {}", e.getMessage());
            log.error("╚═══════════════════════════════════════════════════════════════");
            log.error("异常详情:", e);
            
            return ResponseEntity.status(500)
                    .body(ApiResponse.error("工单创建失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建工单（极速版）
     * 最小化所有同步操作，追求极致响应速度
     */
    @PostMapping("/ultra-fast")
    @Operation(summary = "创建工单（极速版）", 
               description = "极致性能优化，最快响应速度")
    @RequirePermission(roles = {"CUSTOMER", "AGENT", "ADMIN"})
    public ResponseEntity<ApiResponse<TicketDto>> createUltraFast(@Valid @RequestBody CreateTicketRequest req) {
        String requestId = "ULTRA-" + System.currentTimeMillis();
        long startTime = System.currentTimeMillis();
        
        try {
            // 最小化操作
            User creator = userService.findById(req.creatorId())
                    .orElseThrow(() -> new RuntimeException("创建者不存在"));
            
            Ticket ticket = Ticket.builder()
                    .title(req.title())
                    .description(req.description())
                    .descriptionDetail(req.descriptionDetail())
                    .priority(req.priority() != null ? req.priority() : TicketPriority.MEDIUM)
                    .createdBy(creator)
                    .customer(req.customerId() != null ? 
                            userService.findById(req.customerId()).orElse(creator) : creator)
                    .build();
            
            // 极速保存
            Ticket saved = ticketServiceOptimized.createUltraFast(ticket, creator);
            TicketDto dto = SimpleMappers.toTicketDto(saved);
            
            long totalTime = System.currentTimeMillis() - startTime;
            log.info("⚡ [{}] 极速创建完成 - {}ms | ID: {}", requestId, totalTime, saved.getId());
            
            return ResponseEntity.ok(ApiResponse.success("工单创建成功", dto));
            
        } catch (Exception e) {
            long errorTime = System.currentTimeMillis() - startTime;
            log.error("❌ [{}] 极速创建失败 - {}ms: {}", requestId, errorTime, e.getMessage());
            return ResponseEntity.status(500)
                    .body(ApiResponse.error("工单创建失败: " + e.getMessage()));
        }
    }
}

